#!/usr/bin/env python
# -*- coding:utf-8 -*-

import math

from app import db
from controller.upvoteInfoController import UpvoteInfoController
from models.upvoteInfoModel import UpvoteInfo
from models.passageInfoModel import PassageInfo
from utils import commons
from utils.response_code import RET, error_map_EN
from utils.loggings import loggings
from utils.validate_operate import verify_operator_object
from controller.userInfoController import UserInfoController


class UpvoteInfoService(UpvoteInfoController):
    @classmethod
    @verify_operator_object([99, ], UserInfoController)
    def joint_query(cls, **kwargs):
        try:
            filter_list = []
            filter_list.append(cls.IsDelete == 0)
            if kwargs.get('AutoID'):
                filter_list.append(cls.AutoID == kwargs.get('AutoID'))
            if kwargs.get('UUserID'):
                filter_list.append(cls.UUserID == kwargs.get('UUserID'))
            if kwargs.get('PassageID'):
                filter_list.append(cls.PassageID == kwargs.get('PassageID'))
            if kwargs.get('IsDelete'):
                filter_list.append(cls.IsDelete == kwargs.get('IsDelete'))
            if kwargs.get('CreateTime'):
                filter_list.append(cls.CreateTime == kwargs.get('CreateTime'))

            page = int(kwargs.get('Page', 1))
            size = int(kwargs.get('Size', 10))

            upvoteInfo_info = db.session.query(UpvoteInfo.AutoID, UpvoteInfo.UUserID, UpvoteInfo.PassageID,
                                               UpvoteInfo.IsDelete, UpvoteInfo.CreateTime).filter(*filter_list)

            count = upvoteInfo_info.count()
            pages = math.ceil(count / size)
            upvoteInfo_info = upvoteInfo_info.limit(size).offset((page - 1) * size).all()

            if not upvoteInfo_info:
                return {'code': RET.NODATA, 'message': error_map_EN[RET.NODATA], 'error': 'No data to update'}

            # 处理返回的数据
            results = commons.query_to_dict(upvoteInfo_info)
            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'totalCount': count, 'totalPage': pages,
                    'data': results}

        except Exception as e:
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'error': str(e)}
        finally:
            db.session.close()

    @classmethod
    def upvote(cls, **kwargs):
        try:
            filter_list=[PassageInfo.AutoID == kwargs.get('PassageID')]
            passageInfo_info = db.session.query(PassageInfo.PostAuthorID,PassageInfo.UpVoteNum).filter(*filter_list)
            passageInfo_info = passageInfo_info.first()
            if not passageInfo_info:
                return {'code': RET.NODATA, 'message': error_map_EN[RET.NODATA], 'error': 'No data to update'}
            results = commons.query_to_dict(passageInfo_info)
            query_data={'UUserID':kwargs.get('UUserID'),'PassageID':kwargs.get('PassageID')}
            upvoteInfo = cls.get(**query_data)

            if upvoteInfo.get('code') == RET.OK:
                return {'code': RET.DATAEXIST, 'message': error_map_EN[RET.DATAEXIST],
                    'error':'the user had upvoted yet'}

            #二次查询减少数据冗余
            filter_list=[cls.IsDelete == 1,cls.UUserID == kwargs.get('UUserID'),cls.PassageID == kwargs.get('PassageID')]
            reback_data = db.session.query(UpvoteInfo).filter(*filter_list)
            reback_data=reback_data.all()
            if reback_data:
                reback_data = commons.query_to_dict(reback_data)
                reback_data = {
                    'AutoID':reback_data[0].get('AutoID'),
                    'IsDelete':0
                }
                cls.update(**reback_data)
                # 更新文章表点赞数
                from controller.passageInfoController import PassageInfoController
                update_data = {'AutoID': kwargs.get('PassageID'), 'UpVoteNum': int(results.get('UpVoteNum')) + 1}
                PassageInfoController.update(**update_data)
                return {'code': RET.OK, 'message': error_map_EN[RET.OK],
                        'data': 'reback upvote successfully'}

            # 自己点赞自己置为已读不再显示在消息通知中
            if kwargs.get('UUserID') == results.get('PostAuthorID'):
                kwargs['IsRead'] = 1
            else:
                kwargs['IsRead'] = 0
            cls.add(**kwargs)
            # 处理返回的数据


            #更新文章表点赞数
            from controller.passageInfoController import PassageInfoController
            update_data = {'AutoID': kwargs.get('PassageID'),'UpVoteNum':int(results.get('UpVoteNum'))+1}
            PassageInfoController.update(**update_data)

            return {'code': RET.OK, 'message': error_map_EN[RET.OK],
                    'data': update_data}

        except Exception as e:
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'error': str(e)}
        finally:
            db.session.close()

    @classmethod
    def cancelupvote(cls, **kwargs):
        try:
            filter_list = [cls.IsDelete == 0]

            if kwargs.get('UUserID'):
                filter_list.append(cls.UUserID == kwargs.get('UUserID'))
            if kwargs.get('PassageID'):
                filter_list.append(cls.PassageID == kwargs.get('PassageID'))


            upvoteInfo_info = db.session.query(UpvoteInfo.AutoID, UpvoteInfo.UUserID, UpvoteInfo.PassageID,
                                               UpvoteInfo.IsDelete, UpvoteInfo.CreateTime).filter(*filter_list)


            upvoteInfo_info = upvoteInfo_info.first()

            if not upvoteInfo_info:
                return {'code': RET.NODATA, 'message': error_map_EN[RET.NODATA], 'error': 'you hadnt upvote yet'}

            # 处理返回的数据
            results = commons.query_to_dict(upvoteInfo_info)
            deletedata={
                'AutoID':results.get('AutoID')
            }
            # 点赞数减1
            filter_list=[PassageInfo.IsDelete ==0,PassageInfo.AutoID==kwargs.get('PassageID')]
            passageInfo_info = db.session.query( PassageInfo.UpVoteNum
                                               ).filter(*filter_list)
            passageInfo_info = passageInfo_info.first()
            if not passageInfo_info:
                return {'code': RET.NODATA, 'message': error_map_EN[RET.NODATA], 'error': 'the passage has deleted'}

            # 处理返回的数据
            results2 = commons.query_to_dict(passageInfo_info)
            cls.delete(**deletedata)
            from controller.passageInfoController import PassageInfoController
            update_data={
                'AutoID':kwargs.get('PassageID'),
                'UpVoteNum':int(results2.get('UpVoteNum'))-1
            }
            PassageInfoController.update(**update_data)
            return {'code': RET.OK, 'message': error_map_EN[RET.OK],
                    'data': "successfully delete"}

        except Exception as e:
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'error': str(e)}
        finally:
            db.session.close()



